{% load i18n %}
<form role="form" method="post" action="{{request.prefix}}/execute/launch/importfromfolder/">{% csrf_token %}
  <table>
    <tr>
      <td style="vertical-align:top; padding-left: 15px">
        <button type="submit" class="btn btn-primary" id="importfromfolder" value="{% trans "import"|capfirst %}">{% trans "import"|capfirst %}</button>
      </td>
      <td colspan="6" style="padding-left:15px">
        <p>{% trans "Import CSV or Excel files from the data folder. The file names must match the names of data objects and the first line in the file must contain the field names." %}</p>
      </td>
    </tr>
    <tr>
      <td></td>
      <td style="padding-left:15px"><strong>{% trans 'file name'|capfirst %}</strong></td>
      <td><strong>{% trans 'size'|capfirst %}</strong></td>
      <td><strong>{% trans 'changed'|capfirst %}</strong></td>
      <td>
        <span class="btn btn-xs btn-primary" style="margin-bottom:5px" data-toggle="tooltip" data-placement="top" data-original-title="{% trans 'Upload data files' %}"
          onclick="import_show('{% trans 'Copy files to folder' %}',null,true,uploadfilesajax)">
          <span class="fa fa-arrow-up"></span>
        </span>
      </td>
      <td>
        <span class="btn btn-xs btn-primary" style="margin-bottom:5px" data-toggle="tooltip" 
           data-placement="top" data-original-title="{% trans "Download all files" %}"
           onClick="downloadImportFile(0)">
          <span class="fa fa-arrow-down"></span>
        </span>        
      </td>
      <td>
        <div class="btn btn-xs btn-danger deletefile" style="margin-bottom:5px" data-toggle="tooltip" data-placement="top" data-original-title="{% trans 'Delete all files' %}" onClick="deleteImportFile(0, {{filestoupload}})">
          <span class="fa fa-close"></span>
        </div>
      </td>
    </tr>
    {% for j in filestoupload %}
    <tr data-file="{{j.0}}">
      <td></td>
      <td style="padding-left:15px">{{j.0}}</td>
      <td>{{j.2}}</td>
      <td>{{j.1}}</td>
      <td></td>
      <td>
        <div class="btn btn-xs btn-primary downloadfile" style="margin-bottom:5px" data-toggle="tooltip" data-placement="top" data-original-title="{% trans "Download file" %}" onClick="downloadImportFile(0, '{{j.0}}')">
          <span class="fa fa-arrow-down"></span>
        </div>
      </td>
      <td>
        <div class="btn btn-xs btn-danger deletefile" style="margin-bottom:5px" data-toggle="tooltip" data-placement="top" data-original-title="{% trans "Delete file" %}" onClick="deleteImportFile(0, '{{j.0}}')">
          <span class="fa fa-close"></span>
        </div>
      </td>
    </tr>
    {% endfor %}
  </table>
</form>
<script>
var xhr = {abort: function () {}};
var uploadfilesajax = {
  url: '{{request.prefix}}/execute/uploadtofolder/0/',
  success: function (data) {
    var el = $('#uploadResponse');
    el.empty();
    $("#animatedcog").css('visibility','hidden');
    var lines = data.split('\\n');
    for (var i = 0; i < lines.length; i++) {
      el.append(lines[i] + '<br>');
    }
    if (el.attr('data-scrolled')!== "true") {
      el.attr('data-scrolled', el[0].scrollHeight - el.height());
      el.scrollTop(el[0].scrollHeight - el.height());
    }
    if (document.queryCommandSupported('copy'))
      $('#copytoclipboard').show();
    $('#canceluploadbutton').hide();
    $('#cancelimportbutton').hide();
    $('#cancelbutton').one('click', function() {location.reload();});
  },
  error: function (result, stat, errorThrown) {
    var el = $('#uploadResponse');
    el.empty();
    $("#animatedcog").css('visibility','hidden');
    var lines = result.responseText.split('\\n');
    for (var i = 0; i < lines.length; i++) {
      el.append(lines[i] + '<br>');
    }
    if (el.attr('data-scrolled')!== "true") {
      el.attr('data-scrolled', el[0].scrollHeight - el.height());
      el.scrollTop(el[0].scrollHeight - el.height());
    }
    if (document.queryCommandSupported('copy'))
      $('#copytoclipboard').show();
    $('#canceluploadbutton').hide();
    $('#cancelimportbutton').hide();
    }
};

function deleteImportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  var dialogcontent;
  if (typeof filename === 'object') {
    dialogcontent = "{% trans 'You are about to delete all files' %}";
    var oldfilename = filename;
    filename = 'AllFiles';
  } else {
    dialogcontent = interpolate("{% trans 'You are about to delete file %s' %}", [filename]);
  }

  $("#popup").html('<div class="modal-dialog">'+
    '<div class="modal-content">'+
      '<div class="modal-header">'+
        '<h4 class="modal-title">{% trans 'Delete file' %}</h4>'+
      '</div>'+
      '<div class="modal-body"><p>'+
      dialogcontent +
      '</p></div>'+
      '<div class="modal-footer">'+
        '<input type="submit" id="confirmbutton" role="button" class="btn btn-danger pull-right" value="{% trans 'Confirm' %}">'+
        '<input type="submit" id="cancelbutton" role="button" class="btn btn-primary pull-left" data-dismiss="modal" value="{% trans 'Cancel' %}">'+
      '</div>'+
    '</div>'+
  '</div>' )
  .modal('show');

  $('#confirmbutton').on('click', function() {
    $.ajax({
      url: "{{request.prefix}}/execute/deletefromfolder/" + folder + "/" + filename + "/",
      type:  ("delete").toUpperCase(),
      success: function () {
        if (filename === 'AllFiles') {
          $("#popup .modal-body>p").text("{% trans 'All data files were deleted' %}");
        } else {
          $("#popup .modal-body>p").text(interpolate("{% trans 'File %s was deleted' %}", [filename]));
        }
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {$("#popup").hide();});
        location.reload();
      },
      error: function (result, stat, errorThrown) {
        var filelist = result.responseText.split(' / ');
        var elem = $("#popup .modal-body>p");
        if (filelist.length === 1) {
          elem.text(interpolate("{% trans 'File %s was not deleted' %}", [filename]));
        } else {
          for (var i = 1; i < filelist.length; i++) {
            if (i === 1) {
              elem.text(interpolate("{% trans 'File %s was not deleted' %}", [filelist[i]]));
            } else {
              elem.parent().append('<p>'+interpolate("{% trans "File %s was not deleted" %}", [filelist[i]])+'</p>');
            }
          }
        }
        $("#popup .modal-body>p").addClass('alert alert-danger');
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {$("#popup").hide();});
        }
    })
  })
}
function downloadImportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  if (typeof filename === 'undefined')
    window.open(
      "{{request.prefix}}/execute/downloadfromfolder/" + folder + "/",
      '_blank'
      );
  else
    window.open(
      "{{request.prefix}}/execute/downloadfromfolder/" + folder + "/" + filename + '/',
      '_blank'
      );
}
</script>
